package pers.xiaoliang.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @version v1.0
 * @description: synchronized使用
 * @author: xiaoliang.liu
 * @date: 2018/7/28 11:14
 */
@Slf4j
public class SynchronizationTest1 {


    /**
     * synchronized修饰代码块(锁是执行这个代码块的对象)
     * @param j
     */
    public void test1(int j) {
        synchronized (this) {
            for (int i = 0; i < 100; i++) {
                log.info("test1 - :{} {}", j, i);
            }
        }
    }

    /**
     * synchronized修饰方法(锁是调用这个方法的对象)
     * @param j
     */
    public synchronized void test2(int j) {
        for (int i = 0; i < 100; i++) {
            log.info("test2 - :{},  {}", j, i);
        }
    }


    public static void main(String[] args) {
        SynchronizationTest1 synchronizationTest1 = new SynchronizationTest1();
        SynchronizationTest1 synchronizationTest2 = new SynchronizationTest1();

        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> {
            synchronizationTest1.test2(1);
        });

        executorService.execute(() -> {
            synchronizationTest2.test2(2);
        });
    }
}
